<template>
	<view class="orderSubmit">
		<view class="orderSubmit-header mt10 mb10">
			<Caddress @addressId="addressId" />
		</view>
		<view v-for="(item,index) in tableData" :key="index" class="orderSubmit-item mb10">
			<view class="orderSubmit-item-header flex">
				<u--image :showLoading="true" :src="item.admin.avatar[0].url" width="60rpx" height="60rpx"
					radius="10rpx" @click="toAdmin(item.adminId)" />
				<text class="fs14 ml5" style="margin-right: 12rpx"
					@click="toAdmin(item.adminId)">{{ item.admin.userName }}</text>
			</view>
			<u-line />
			<view class="orderSubmit-item-content flex">
				<u--image :showLoading="true" :src="item.iconId[0].url" width="180rpx" height="180rpx" radius="20rpx"
					@click="toGoodsDetails(item.id)" />
				<view class="orderSubmit-item-content-right ml10">
					<text class="u-line-1 fs13" @click="toGoodsDetails(item.id)">{{ item.name || '未命名商品' }}</text>
					<view class="flexCol mt5 mb5">
						<view v-for="value in item.sku_List" :key="value._id"
							class="orderSubmit-item-content-right-skuItem mb5 flex fs12">
							<view class="orderSubmit-item-content-right-skuItem-left flex mr10">
								<text class="u-line-1">{{ value.sku_name_arr | skuListText }}</text>
								<text class="ml10">x{{ value.cart_num || 0 }}</text>
							</view>
						</view>
					</view>
					<text style="color: #ff4b02">￥{{ item.goodsItemPrices.toFixed(2)  }}</text>
				</view>
			</view>
			<view class="orderSubmit-item-footer flex">
				<text class="fs14">订单备注：</text>
				<u--textarea v-model="item.descText" placeholder="请输入内容" autoHeight count border="bottom" />
			</view>
		</view>
		<Cbottomview>
			<view class="orderSubmit-submit flex">
				<view class="flex mr10">
					<text class="fs12" style="word-break: keep-all;">合计：</text>
					<text style="color: #ff4b02;" class="fs12">￥</text>
					<text style="color: #ff4b02;" class="fs20">{{ orderTotalPrices.toFixed(2) }}</text>
				</view>
				<u-button text="提交订单" @click="submitOrder" />
			</view>
		</Cbottomview>
		<u-popup :show="payPopup.visible" closeable :round="10" @close="closePayPopup">
			<view class="orderSubmit-payPopup">
				<view class="orderSubmit-payPopup-header flexCenter fs18 mb20">
					付款详情
				</view>
				<view class="orderSubmit-payPopup-content">
					<view v-for="(item, index) in payPopup.orderId" :key="index"
						class="orderSubmit-payPopup-content-item flex">
						<text class="labelColor" style="flex: 0 0 30%;">订单信息 {{ index === 0 ? '' : index + 1 }}</text>
						<text class="valueColor u-line-1">订单号{{ item.orderId }}</text>
					</view>
					<view class="orderSubmit-payPopup-content-item flex">
						<text class="labelColor">支付账号</text>
						<text class="valueColor u-line-1">{{ userInfo.phone || '未绑定手机号' }}</text>
					</view>
					<view class="orderSubmit-payPopup-content-item flex">
						<text class="labelColor">支付方式</text>
						<text class="valueColor u-line-1">虚拟支付</text>
					</view>
					<view class="orderSubmit-payPopup-content-item flex">
						<text class="valueColor fs16">需付款</text>
						<text class="u-line-1 fs18" style="color: #303133;">{{ orderTotalPrices.toFixed(2) }}元</text>
					</view>
					<view class="orderSubmit-payPopup-content-menu mt40">
						<u-button text="确认付款" @click="confirmPay" />
					</view>
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
	import setSkuData from "@/utils/set_Sku_data.js"
	import {
		mapGetters
	} from 'vuex'
	export default {
		name: 'OrderSubmit',
		options: {
			styleIsolation: "shared"
		}, // 父组件设置 options.styleIsolation 可穿透子组件，以及页面
		mixins: [setSkuData],
		filters: {
			// 转换选择的sku规格名称
			skuListText(data) {
				let string = ''
				data.forEach((item, index) => {
					string += `${item}${index === data.length -1 ? '' : ','}`
				})
				return string
			}
		},
		data() {
			return {
				order: [], // 路由订单参数
				tableData: [], // 商品数据
				selectAddressId: '', // 选择得订单收获子地址
				payPopup: { // 支付对话框
					visible: false,
					orderId: [], // 订单号
				}
			}
		},
		computed: {
			...mapGetters(['userInfo']),
			orderTotalPrices() {
				const prices = this.tableData.map(item => item.goodsItemPrices)
				return prices.length > 0 ? prices.reduce((n, m) => n + m) : 0
			}
		},
		onShow() {
			const routes = getCurrentPages()
			const order = routes[routes.length - 1]?.options?.order
			this.order = JSON.parse(order)
			this.getList() // 获取商品数据
		},
		methods: {
			// 确认付款（虚拟支付修改订单状态）
			async confirmPay() {
				const promise_all = await Promise.all(this.payPopup.orderId.map(item => this.$order
					.orderChangeOrderStatus({
						id: item.id,
						orderStatus: 'DFH'
					})))
				if (promise_all.length === this.payPopup.orderId.length) {
					this.showToast('支付成功')
					// 跳转到订单页面
					uni.navigateTo({
						url: `/pages/order/index`,
						animationType: 'pop-in',
						animationDuration: 200
					})
				}
			},
			// 关闭支付对话框
			closePayPopup() {
				this.payPopup.visible = false
			},
			// 提交订单
			async submitOrder() {
				if (!this.selectAddressId) {
					this.showToast('请选择收货地址');
					return
				}
				const cartIds = []
				const data = this.tableData.map(item => {
					if (item.none_sku) { // 无规格
						item.cartId && cartIds.push(item.cartId)
					} else { // 多规格
						const ids = item.sku_List.map(item => item.cartId).filter(item => item)
						ids.length > 0 && cartIds.push(...ids)
					}
					return {
						goodsId: item.id,
						// 无规格商品 不传listId
						list: item.none_sku ? [{
							cart_num: item.cart_num
						}] : item.sku_List.map(i => {
							return {
								listId: i._id,
								cart_num: i.cart_num
							}
						}),
						none_sku: item.none_sku ? true : false,
						adminId: item.adminId,
						descText: item.descText,
						addressId: this.selectAddressId
					}
				})
				const promise_all = await Promise.all(data.map(item => this.$order.orderAdd(item)))
				if (promise_all.length === data.length) {
					// this.showToast('提交成功')
					this.payPopup.orderId = promise_all.map(item => item.data) // 集合订单号信息
					this.payPopup.visible = true
					cartIds.length > 0 && this.$shopCart.shopCartDelete({
						cartIds: cartIds.toString()
					})
				}
			},
			// 跳转到商品详情
			toGoodsDetails(goodsId) {
				uni.navigateTo({
					url: `/pages/adminUser/adminUser?goodsId=${goodsId}`,
					animationType: 'pop-in',
					animationDuration: 200
				})
			},
			// 跳转到店铺详情
			toAdmin(adminId) {
				uni.navigateTo({
					url: `/pages/adminUser/adminUser?adminId=${adminId}`,
					animationType: 'pop-in',
					animationDuration: 200
				})
			},
			// 选择地址回调
			addressId(addressId) {
				this.selectAddressId = addressId
			},
			// 初始化
			async getList() {
				const promise_all = Promise.all(this.order.map(item => this.$goods.goodsGoodDetails({
					id: item.goodsId
				})))
				let data = await promise_all // 商品数据
				data = data.map(item => {
					item.data['newList'] = []
					return item.data
				})
				// 格式化订单数据
				this.order.forEach(item => {
					const index = data.findIndex(i => item.goodsId === i.id)
					if (data[index].none_sku) { // 无规格商品合并
						data[index]['cartId'] = item.list[0].cartId
						data[index]['cart_num'] = item.list[0].cart_num
					} else { // 多规格商品
						item.list.forEach(value => { // 循坏传过来的规格组合列表，合并至商品list数据
							const skuIndex = data[index].list.findIndex(i => i.id === value.listId)
							const newSku = Object.assign(data[index].list[skuIndex], value)
							data[index].newList.push(newSku)
						})
					}
				})
				// 格式化商品数据格式
				data.forEach(item => {
					item['list'] = item.newList
					if (item.none_sku) { // 无规格
						item['sku_List'] = this.setSku_list(item, 'none')
						item['spec_List'] = this.setSpec_list(item.skuList, 'none') // 规格列表
					} else { // 多规格
						item['sku_List'] = this.setSku_list(item)
						item['spec_List'] = this.setSpec_list(item.skuList) // 规格列表
					}
				})
				const promisr_all = data.map(item => this.$adminUser.adminUserGetDetails({
					adminId: item.adminId
				}))
				const admin_all = await Promise.all(promisr_all)
				data.forEach(item => {
					const index = admin_all.findIndex(i => i.data.id === item.adminId)
					item['admin'] = admin_all[index].data
				})
				this.tableData = data
				this.computeGoodsItemPrices() // 计算单个商品选择的组合列表总价
				console.log(this.tableData, 'data')
			},
			// 计算单个商品选择的组合列表总价 && 添加订单备注字段
			computeGoodsItemPrices() {
				this.tableData.forEach(data => {
					data['descText'] = ''
					const prices = data.sku_List.map(item => item.price * item.cart_num)
					data['goodsItemPrices'] = prices.reduce((n, m) => n + m)
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	.labelColor {
		color: #909399;
	}

	.valueColor {
		color: #606266;
	}

	.orderSubmit {
		padding: 10rpx 15rpx;

		&-header {}

		&-item {
			padding: 15rpx 20rpx;
			background-color: #FFFFFF;
			border-radius: 10rpx;

			&-content {
				padding: 20rpx;
				display: flex;

				&-right {
					display: flex;
					flex-direction: column;
					justify-content: space-between;

					&-skuItem {
						color: #909399;
						justify-content: space-between;

						&-left {
							width: fit-content;
							padding: 5rpx 20rpx;
							background: rgba(0, 0, 0, .08);

							/deep/ .u-icon {
								margin-left: 8rpx;
							}
						}

					}
				}
			}
		}

		&-submit {
			padding: 10rpx 20rpx;

			/deep/ .u-button {
				background-color: $uni-color-primary;
				color: #fff;
			}
		}

		&-payPopup {
			padding: 20rpx 30rpx;

			&-header {
				padding-top: 20rpx;
			}

			&-content {
				&-item {
					padding: 15rpx 0;
					justify-content: space-between;
				}

				&-menu {
					/deep/ .u-button {
						background-color: $uni-color-primary;
						color: #fff;
					}
				}
			}
		}
	}
</style>
